package com.mai4j.maiadmin.controller.api.monitor;

import com.mai4j.maiadmin.misc.StructMapper;
import com.mai4j.maiadmin.model.dto.PageDTO;
import com.mai4j.maiadmin.model.dto.SqlHistoryDTO;
import com.mai4j.maiadmin.model.http.datatables.Datatable;
import com.mai4j.maiadmin.model.http.datatables.response.DatatableResp;
import com.mai4j.maiadmin.service.SqlHistoryService;
import com.mai4j.maiadmin.support.security.aop.annotation.RequiresAuthentication;
import com.mai4j.maiadmin.support.web.binding.ReqParam;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.stream.Collectors;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@RequiresAuthentication
@RestController
@RequestMapping("/api/monitor/sql-history")
public class ApiSqlHistoryController {

    private final SqlHistoryService sqlHistoryService;

    public ApiSqlHistoryController(SqlHistoryService sqlHistoryService) {
        this.sqlHistoryService = sqlHistoryService;
    }

    @PostMapping("/datatable")
    public ResponseEntity<DatatableResp> datatable(@ReqParam Datatable datatable) {
        PageDTO<SqlHistoryDTO> pageDTO = sqlHistoryService.paginate(datatable);
        return ResponseEntity.ok(new DatatableResp()
                .setDraw(datatable.getDraw())
                .setRecordsFiltered(pageDTO.getTotalRow())
                .setRecordsTotal(pageDTO.getTotalRow())
                .setData(pageDTO.getList()
                        .stream()
                        .map(StructMapper.INSTANCE::sqlHistoryDTOToSqlHistoryVO)
                        .collect(Collectors.toList())));
    }
}
